package com.kdyzm.typora.upload.plugin.service.impl;

import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kdyzm.typora.upload.plugin.model.TokenHeader;
import com.kdyzm.typora.upload.plugin.model.UploadResult;
import com.kdyzm.typora.upload.plugin.properties.ConfigProperties;
import com.kdyzm.typora.upload.plugin.service.UploadService;
import com.kdyzm.typora.upload.plugin.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.HttpCookie;

/**
 * @author kdyzm
 */
@Service
@Slf4j
public class DefaultUploadServiceImpl implements UploadService {

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private ConfigProperties configProperties;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String upload(String filePath) throws JsonProcessingException {
        TokenHeader token = tokenUtils.getToken();
        String body = HttpRequest
                .post(configProperties.getUploadUrl())
                .form("file", new File(filePath))
                .cookie(new HttpCookie(token.getKey(), token.getValue()))
                .execute()
                .body();
        UploadResult uploadResult = objectMapper.readValue(body, UploadResult.class);
        String path = uploadResult.getPath();
        return configProperties.getHomePage() + path;
    }
}
